package com.dhecp.project.base.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.annotation.Log;
import com.dhecp.common.annotation.RepeatSubmit;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.core.page.TableDataInfo;
import com.dhecp.common.enums.BusinessType;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.ModuleTable;
import com.dhecp.core.layui.GridColumnsPropertyModel;
import com.dhecp.project.base.domain.LogsticsServer;
import com.dhecp.project.base.service.LogsticsServerService;
import com.dhecp.project.business.domain.ProductBasis;
import com.dhecp.project.common.controller.BaseModuleController;
import com.dhecp.project.system.domain.SysDictionaryForPageField;
import com.dhecp.project.system.service.SysDictionaryForFieldService;

/**
 * 公司信息 控制层
 * @author DH-Xxj
 * @version 2019年11月4日
 */
@Controller
@RequestMapping("/base/logsticsserver")
public class LogsticsServerController extends BaseModuleController {
    private String prefix = "base/logsticsserver";
    private String moduleTable = ModuleTable.LOGSTICS_SERVER;

    
    @Autowired
    private LogsticsServerService logsticsServerService;

    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private GridColumnsPropertyModel gridColumnsPropertyModel;

    /**
     *@Description: 打开查询列表页
     *@Param: [params]
     *@return: org.springframework.web.servlet.ModelAndView
     *@Author: hlf
     *@date: 2022-05-09 11:39
     */
    @RequiresPermissions("base:logsticsserver:view")
    @GetMapping()
    public ModelAndView view(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        params.put("entity", new LogsticsServer()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
        params.put("prefix","base/logsticsserver/logsticsserver"); //页面路径
        params.put("toolBarWidth", 80);
        params.put("checkBox", "yes");

        ModelAndView mv = this.openListPage(params);
        mv.addObject("base", "logsticsserver");
//        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        return mv;
    }
	

    /**
     *@Description: 查询页 列表数据
     * @Author: Jason
     * @date: 2022-09-02 11:41
     */
    @RequiresPermissions("base:logsticsserver:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
        List<LogsticsServer> list = new ArrayList<LogsticsServer>();
        try {
            list = logsticsServerService.queryList(params);
        } catch (Exception e) {
            e.printStackTrace();
            return getDataTable(this.getExceptionMessage(e).toString());
        }
        return getDataTable(list);
    }
	
	/**
     * 打开物流服务商新增页
     * @Author: Jason
     * @date: 2022-09-02 11:41
	 */
    @RequiresPermissions("base:logsticsserver:add")
    @GetMapping("/add")
    public ModelAndView add(@RequestParam Map<String, Object> params){
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new ProductBasis()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
		List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>(); //字段字典
		List<Object> fieldsList = new ArrayList<Object>(); 			//生成控件的字段和属性
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 	//隐藏的字段和属性
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        try{
            dictionaryForFieldMap = dictionaryForFieldService.queryFieldAttributesMap(params);
            if (dictionaryForFieldMap.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
                ajaxResult = AjaxResult.success("数据获取成功。");
            }

        	params.put("getFieldAttributesType", "pagenotingrid"); 	//非表格字段
    		dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
            	for (SysDictionaryForPageField dicFields : dicFieldsList){
            		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
            		fieldsListMap.put("fieldContent", "");
            		
            		if (fieldsListMap.get("fieldFrontType") == null){
            			fieldsListMap.put("fieldFrontType", "t_text");
            		}
            		
            		if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){	//显示的字段
            			fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
            		}else {	//隐藏的字段
            			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
            		}
            	}
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("pageType","add"); //页面类型：新增（add）、修改（edit）
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap)); //各字段及属性
        mv.addObject("fieldsList", fieldsList);				//显示的字段
        mv.addObject("fieldsHiddenList", fieldsHiddenList);	//隐藏的字段
        mv.addObject("ajaxResult", ajaxResult);
        mv.setViewName(prefix + "/logsticsserver_add");
        return mv;
    }
    
    /**
     * 打开物流服务商修改页
     * @Author: Jason
     * @date: 2022-09-02 11:41
     */
    @RequiresPermissions("base:logsticsserver:edit")
    @GetMapping("/edit")
    public ModelAndView edit(@RequestParam Map<String, Object> params){
    	
    	params.put("moduleTable", moduleTable);
    	params.put("entity", new LogsticsServer()); //用于获取实体属性名取代对应字典字段名，解决大小写敏感问题
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        List<SysDictionaryForPageField> dicFieldsList = new ArrayList<SysDictionaryForPageField>();
        List<Object> fieldsList = new ArrayList<Object>();
        List<Object> fieldsHiddenList = new ArrayList<Object>(); 			//隐藏的字段和属性
        List<String> fieldRequiredList = new ArrayList<String>();
        try{
        	dicFieldsList = dictionaryForFieldService.queryFieldAttributesList(params);
            if (dicFieldsList.isEmpty()){
                ajaxResult = AjaxResult.error("未获取到字段属性。");
            }else{
            	LogsticsServer logsticsServer = logsticsServerService.queryFirstByGuid(params);
            	if (logsticsServer == null){
            		ajaxResult = AjaxResult.error("没有查到物流服务商[" + params.get("Guid").toString() + "]的信息。");
            	}else{
                	ajaxResult = AjaxResult.success("数据获取成功。");
                	mv.addObject("logsticsServer",logsticsServer);
                	for (SysDictionaryForPageField dicFields : dicFieldsList){
                		Map<String, Object> fieldsListMap = TypeUtils.entityToMap(dicFields);
                		fieldsListMap.put("fieldContent", TypeUtils.entityToMap(logsticsServer).get(fieldsListMap.get("fields")));
                		
                		if ((Integer)fieldsListMap.get("fieldFrontTop") == 1){ //显示的表头
                    		fieldsList.add(TypeUtils.mapToJson(fieldsListMap));
                		}else{ //隐藏的表头
                			fieldsHiddenList.add(TypeUtils.mapToJson(fieldsListMap));
                		}
                		if (dicFields.getFieldFrontRequired() != null && dicFields.getFieldFrontRequired()){
                			fieldRequiredList.add(dicFields.getFields());
                		}
                	}
            	}
            }
        }
        catch(Exception e){
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        mv.addObject("ajaxResult", ajaxResult); //查询结果状态
        mv.addObject("fieldRequiredList", fieldRequiredList); //必填字段
        mv.addObject("fieldsList", fieldsList); //生成控件
        mv.addObject("fieldsHiddenList", fieldsHiddenList); //隐藏的表头
        mv.addObject("type",params .get("type")); //当前页面是否可编辑（0：不可编辑，1：可编辑）
        mv.setViewName(prefix + "/logsticsserver_edit");
        return mv;
    }
    
    /**
	 * 新增物流服务商
     * @author Jason
     * @date: 2022-09-02 21:40
     */
    @Log(title = "新增物流服务商", businessType = BusinessType.INSERT)
    @RequiresPermissions("base:logsticsserver:add")
    @PostMapping("/addpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult addpost(@RequestParam Map<String, Object> params){
		
    	AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsServerService.insertLogsticsServer(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 修改物流服务商
     * @author Jason
     * @date: 2022-09-02 21:40
     */
    @RequiresPermissions("base:logsticsserver:edit")
    @Log(title = "修改公司信息", businessType = BusinessType.UPDATE)
    @PostMapping("/editpost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult editpost(@RequestParam Map<String, Object> params) {
    	
    	System.out.println(JSON.toJSONString(params));
    	
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsServerService.updateLogsticsServer(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
    
    /**
     * 打开物流服务商选择页面
     * @param params
     * @return ModelAndView
     * @author lwl
     */
    @GetMapping("/select")
    public ModelAndView selectModule(@RequestParam Map<String, Object> params){
        params.put("moduleTable", moduleTable);
    	params.put("entity", new LogsticsServer()); //生成表格gridColumns对应的实体，用于获取实体属性生成表格字段
    	params.put("toolBarWidth", 0);
    	if(params.get("pagetype") !=null && params.get("pagetype").toString().equalsIgnoreCase("checkbox"))params.put("checkBox", "yes");
        else params.put("radio", "yes");
        ModelAndView mv = this.getModelAndView();
        AjaxResult ajaxResult = new AjaxResult();
        Map<String, Object> dictionaryForFieldMap = new HashMap<String, Object>();
        
        mv.addObject("fields", TypeUtils.mapToJson(dictionaryForFieldMap));
        mv.addObject("ajaxResult", ajaxResult);
        mv.addObject("gridColumns", gridColumnsPropertyModel.queryGridColumnsPropertyModel(params));
        mv.addObject("prefix", prefix);
        mv.addObject("moduleTable", moduleTable);
        mv.setViewName("common/select");
        return mv;
    }

    /**
     * 删除物流名称
     * @author fxz
     * @date: 2022-09-22
     */
    @RequiresPermissions("base:logsticsserver:delete")
    @Log(title = "删除物流服务商", businessType = BusinessType.DELETE)
    @PostMapping("/deletepost")
    @ResponseBody
    @RepeatSubmit
    public AjaxResult deletepost(@RequestParam Map<String, Object> params) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            ajaxResult= logsticsServerService.deleteLogsticsServer(params);
        }catch (Exception e) {
            ajaxResult = AjaxResult.error(this.getExceptionMessage(e));
        }
        return ajaxResult;
    }
}
